package com.server.sercurity.impl;

import cn.hutool.core.util.ObjectUtil;
import com.server.sercurity.vo.UserDetailsVO;
import com.server.base.entity.SysAdmin;
import com.server.base.entity.SysMenu;
import com.server.base.entity.SysRole;
import com.server.base.service.ISysAdminService;
import com.server.base.service.ISysMenuService;
import com.server.base.service.ISysRoleService;
import com.server.base.vo.AdminLoginSuccessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zgr
 * @date 2023/7/18 10:58
 * @description
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private final ISysAdminService sysAdminService;
    private final ISysRoleService sysRoleService;
    private final ISysMenuService sysMenuService;

    public UserDetailsServiceImpl(ISysAdminService sysAdminService, ISysRoleService sysRoleService, ISysMenuService sysMenuService) {
        this.sysAdminService = sysAdminService;
        this.sysRoleService = sysRoleService;
        this.sysMenuService = sysMenuService;
    }

    @Override
    public UserDetails loadUserByUsername(String adminName) throws UsernameNotFoundException {
        log.info("admin:{}", adminName);
        SysAdmin sysAdmin = sysAdminService.getAdminByName(adminName);
        if (ObjectUtil.isNull(sysAdmin)) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //获取用户所有角色
        List<SysRole> sysRoleList = sysRoleService.selectRolesByAdminId(sysAdmin.getId());
        Set<String> set = sysRoleList.stream().map(s-> "ROLE_"+ s.getRoleKey()).collect(Collectors.toSet());
        log.info("loadUserByUsername set:"+set);
        //获取用户所有权限
        List<SysMenu> sysMenuList = sysMenuService.selectPermsByAdminId(sysAdmin.getId());
        //整理数据
        AdminLoginSuccessVO adminLoginSuccessVO = new AdminLoginSuccessVO();
        adminLoginSuccessVO.setSysAdmin(sysAdmin);
        adminLoginSuccessVO.setMenus(sysMenuList);
        adminLoginSuccessVO.setRoles(sysRoleList);


        List<String> permissions = sysMenuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
        log.info("loadUserByUsername permissions:{}", permissions);
        permissions.addAll(set);
        log.info("loadUserByUsername permissions all:{}", permissions);
        return new UserDetailsVO(adminLoginSuccessVO);
    }
}
